import functools
import os

import jwt
from jwt import exceptions
from flask import Flask, g, request

from applications.common.admin_authorization.jwtconfig import SALT
from applications.common.login import passport_bp
from applications.common.book_info import bookInfo_bp
from applications.common.borrow_info import borrowInfo_bp
from applications.common.searchAndborrow import thebookInfo_bp
from applications.common.licence_info import licenceInfo_bp
from applications.common.violation_info import violationInfo_bp
from applications.config import config

def jwt_authentication():
    """
    1.获取请求头Authorization中的token
    2.判断是否以 Bearer开头
    3.使用jwt模块进行校验
    4.判断校验结果,成功就提取token中的载荷信息,赋值给g对象保存
    """
    # jwt_authentication
    auth = request.headers.get('Authorization')
    g.username = None
    try:
        payload = jwt.decode(auth, SALT, algorithms=['HS256'])
        g.username = payload.get('username')
    except exceptions.ExpiredSignatureError:  # 'token已失效'
        g.username = 'timeoutToken'
    except jwt.DecodeError:  # 'token认证失败'
        g.username = 'failToken'
    except jwt.InvalidTokenError:  # '非法的token'
        g.username = 'illegalToken'
def register_admin_request(app: Flask):
    app.register_blueprint(passport_bp)
    app.register_blueprint(bookInfo_bp)
    app.register_blueprint(borrowInfo_bp)
    app.register_blueprint(thebookInfo_bp)
    app.register_blueprint(licenceInfo_bp)
    app.register_blueprint(violationInfo_bp)
def create_app(config_name=None):
    # 读取配置文件
    if not config_name:
        # 尝试从本地环境中读取
        config_name = os.getenv('FLASK_CONFIG', 'development')

    app = Flask(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

    app.before_request(jwt_authentication)
    # 注册路由
    register_admin_request(app)

    # 引入数据库配置
    app.config.from_object(config[config_name])


    logo()

    return app


def logo():
    print(''''  _  _             _               _                        ___             _ __    _  _             _      __ _   _        _     
 | || |   _  _    | |_    _  _    | |_    _  _      o O O  / __|    ___    | '_ \  | || |    _ _    (_)    / _` | | |_     | |_   
 | __ |  | +| |   |  _|  | +| |   |  _|  | +| |    o      | (__    / _ \   | .__/   \_, |   | '_|   | |    \__, | | ' \    |  _|  
 |_||_|   \_,_|   _\__|   \_,_|   _\__|   \_,_|   TS__[O]  \___|   \___/   |_|__   _|__/   _|_|_   _|_|_   |___/  |_||_|   _\__|  
_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""| {======|_|"""""|_|"""""|_|"""""|_| """"|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""| 
"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'./o--000'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-' 
'
''')
